﻿using System.Security.Cryptography;
using System.Text;

namespace CTP.CRM.Core.Helper
{
    //
    // 摘要:
    //     RSA 加密解密
    public static class RSAContext
    {
        private static readonly string PublicKey;

        private static readonly RSACryptoServiceProvider RsaPublic;

        static RSAContext()
        {
            PublicKey = File.ReadAllText("./fspublickey.key");
            RsaPublic = new RSACryptoServiceProvider();
            ImportPublicKeyFromPEM(RsaPublic, PublicKey);
        }

        //
        // 摘要:
        //     导入公钥
        //
        // 参数:
        //   rsa:
        //
        //   publicKey:
        private static RSACryptoServiceProvider ImportPublicKeyFromPEM(RSACryptoServiceProvider rsa, string publicKey)
        {
            publicKey = publicKey.Replace("-----BEGIN RSA PUBLIC KEY-----", "").Replace("-----END RSA PUBLIC KEY-----", "").Replace("\r", "")
                .Replace("\n", "");
            rsa.ImportRSAPublicKey(Convert.FromBase64String(publicKey), out var _);
            return rsa;
        }

        //
        // 摘要:
        //     导出公钥
        //
        // 参数:
        //   rsa:
        public static string ExportPublicKeyToPEM(RSACryptoServiceProvider rsa)
        {
            return rsa.ExportRSAPublicKeyPem();
        }

        //
        // 摘要:
        //     加密
        //
        // 参数:
        //   encryptedMessage:
        //
        //   bytes:
        public static string Encrypt(byte[] encryptedMessage, out byte[] bytes)
        {
            byte[] bytes2 = (bytes = RsaPublic.Encrypt(encryptedMessage, fOAEP: false));
            return Encoding.UTF8.GetString(bytes2);
        }

        public static string Encrypt(string encryptedMessage)
        {
            byte[] bytes = RsaPublic.Encrypt(Encoding.UTF8.GetBytes(encryptedMessage), fOAEP: false);
            return Encoding.UTF8.GetString(bytes);
        }

        //
        // 摘要:
        //     解码
        //
        // 参数:
        //   encryptedMessage:
        public static string Decrypt(string encryptedMessage)
        {
            byte[] bytes = RsaPublic.Decrypt(Encoding.ASCII.GetBytes(encryptedMessage), fOAEP: false);
            return Encoding.UTF8.GetString(bytes);
        }

        //
        // 摘要:
        //     解码
        //
        // 参数:
        //   encryptedMessage:
        public static string Decrypt(byte[] encryptedMessage)
        {
            byte[] bytes = RsaPublic.Decrypt(encryptedMessage, fOAEP: false);
            return Encoding.UTF8.GetString(bytes);
        }
    }
}
